package com.maezia.tdr.dao.repository;

import com.maezia.tdr.domain.po.Dict;
import com.maezia.tdr.service.DictService;
import com.maezia.tdr.common.CommonConstant;
import com.maezia.tdr.common.redis.BaseRedisRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.util.ObjectUtils;

import java.util.concurrent.TimeUnit;

@Repository
public class AccessTokenRepository extends BaseRedisRepository<String> {

    @Autowired
    private DictService dictService;

    public AccessTokenRepository() {
        super(String.class);
    }

    public void save(String clientId, String accessToken) {
        String redisKey = CommonConstant.ACCESS_TOKEN_KEY + CommonConstant.COLON + clientId;
        if(!stringRedisTemplate.hasKey(redisKey)){
            Dict dict = dictService.getByKey(CommonConstant.ACCESS_TOKEN_KEY);
            stringRedisValueOps.set(redisKey, accessToken, Long.valueOf(dict.getValue()), TimeUnit.HOURS);
        }
    }

    public String get(String clientId) {
        String redisKey = CommonConstant.ACCESS_TOKEN_KEY + CommonConstant.COLON + clientId;
        return stringRedisValueOps.get(redisKey);
    }

    public Long getExpired(String clientId){
        String redisKey = CommonConstant.ACCESS_TOKEN_KEY + CommonConstant.COLON + clientId;
        Long expired = stringRedisTemplate.getExpire(redisKey);
        return ObjectUtils.isEmpty(expired) ? 0L : expired;
    }
}
